<!-- 员工花名册 -->
<template>
  <ContentCard>
    <div style="position: relative">
      <a-collapse
        :default-active-key="['1']"
        :bordered="false"
        v-model:active-key="isCollapse"
        :show-expand-icon="false"
      >
        <a-collapse-item header="" key="1">
          <!-- <template #extra>
          {{ isCollapse == '1' ? '收起' : '展开员工统计数据' }}
        </template> -->
          <div
            style="
              display: flex;
              gap: 10px;
              margin-bottom: 10px;
              margin-right: 20px;
            "
          >
            <!-- <HumenNumberCard
            :list="numberList.list1"
            color1="#96e6c3"
            color2="#4bcfc4"
            style="flex-grow: 1"
          /> -->
            <HumenNumberCard
              :list="numberList.list1"
              color1="#ecf6ff"
              color2="#165dff"
              style="flex: 2"
            />
            <HumenNumberCard
              :list="numberList.list2"
              color1="#F5FDF2"
              color2="#82d62c"
              style="flex: 1.5"
            />
            <HumenNumberCard
              :list="numberList.list3"
              color1="#FFF7F0"
              color2="#f5b45b"
              style="flex: 1"
            />
          </div>

          <a-space direction="vertical" fill>
            <a-tag closable color="blue" size="large" style="width: 100%">
              <template #icon>
                <icon-info-circle />
              </template>
              <span style="width: 100%"
                >温馨提示：当前组织已接近控编人数上线，请注意控制人员规模，避免超出编制。</span
              >
            </a-tag>
            <a-tag closable color="gold" size="large" style="width: 100%">
              <template #icon>
                <icon-info-circle />
              </template>
              <span style="width: 100%"
                >温馨提示：控编人数已经达到人数上限，不可以新增人员。</span
              >
            </a-tag>
            <a-tag closable color="red" size="large" style="width: 100%">
              <template #icon>
                <icon-info-circle />
              </template>
              <span style="width: 100%"
                >温馨提示：控编人数已经超出人数上限，请优化组织结构。</span
              >
            </a-tag>
          </a-space>
        </a-collapse-item>
      </a-collapse>
      <!-- <span @click="changeCollapse" class="collapseBtn">
        {{ isCollapse == '1' ? '收起' : '展开员工统计数据' }}</span
      > -->
      <div
        class="collapseBtn"
        :style="{
          top: isCollapse === '1' ? '60px' : '0'
        }"
      >
        <a-tooltip
          content="展开员工统计数据"
          v-if="isCollapse !== '1'"
          position="left"
        >
          <icon-caret-right @click="changeCollapse" />
        </a-tooltip>
        <a-tooltip content="收起" v-else position="left">
          <icon-caret-down @click="changeCollapse" />
        </a-tooltip>
      </div>
    </div>

    <ConditionBox :margin-bottom="20" :margin-top="20">
      <template #left>
        <a-space>
          <a-input-search
            :style="{ width: '220px' }"
            placeholder="姓名"
            search-button
            @search="onSearch"
            @press-enter="onSearch"
            v-model="nameSearch"
          />
          <a-input-search
            :style="{ width: '220px' }"
            placeholder="手机号"
            search-button
            @search="onSearch"
            @press-enter="onSearch"
            v-model="phoneSearch"
          />
          <a-dropdown @select="batchSelect">
            <a-button>
              <template #icon>
                <icon-font
                  :style="{
                    position: 'relative',
                    top: '1.3px'
                  }"
                  type="icon-a-All-applicationquanbu"
                  :size="20"
                ></icon-font>
              </template>
              <template #default>批量人事操作</template>
            </a-button>
            <template #content>
              <a-doption
                v-for="item in batchOperation"
                :key="item.value"
                :value="item.value"
              >
                <template #icon>
                  <icon-font :type="item.icon" :size="20"></icon-font>
                </template>
                {{ item.label }}
              </a-doption>
            </template>
          </a-dropdown>
          <IssuingCertificateModal ref="refIssuingCertificateModal" />
        </a-space>
      </template>
      <template #right>
        <a-space size="medium">
          <a-button type="primary" @click="add">添加新员工</a-button>
          <a-button type="outline" @click="importVisible = true">导入</a-button>
          <a-button type="outline" @click="exportSettingVisible = true"
            >导出</a-button
          >
          <a-dropdown @select="moreControlSelect" v-model="moreSelect">
            <a-button type="outline"
              >更多功能
              <icon-down
                :style="{
                  marginLeft: '5px'
                }"
              />
            </a-button>
            <template #content>
              <a-doption
                v-for="item in moreControl"
                :key="item.value"
                :value="item.value"
                >{{ item.label }}
              </a-doption>
            </template>
          </a-dropdown>
        </a-space>
      </template>
    </ConditionBox>
    <TableTurn :tableData="getTableData" :args="args" ref="tableRef">
      <a-table-column :width="80">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <TableControlShow
        :selectedHeader="selectedHeader"
        :showCtlCodeArr="showCtlCodeArr"
        :specialCtlCode="['C62B8DC31189847E0972B5D8F721404B1']"
      >
        <template #custom="record">
          <div
            v-if="
              record.controlData.ctlCode === 'C62B8DC31189847E0972B5D8F721404B1'
            "
            :style="{
              textAlign: 'left',
              paddingLeft:
                record.cellData.level > 2
                  ? '32px'
                  : (record.cellData.level - 1) * 16 + 'px',
              cursor: 'pointer'
            }"
          >
            <span
              @click="
                goDetail(
                  record.cellData.id,
                  record.cellData.useTemplate.ownerType
                )
              "
            >
              <a-avatar
                :size="40"
                :imageUrl="record.cellData.headPortrait"
                :style="{ backgroundColor: '#3c6eff' }"
              >
                {{ record.cellData.name.slice(-2) }}
              </a-avatar>
              {{ record.cellData[record.controlData.ctlCode] }}
            </span>
          </div>
        </template>
      </TableControlShow>
      <a-table-column :width="80" title="办理状态">
        <template #cell="{ record }">
          <span
            :class="{
              'text-gray': record.proceduresStatus === 0,
              'text-blue': record.proceduresStatus === 1,
              'text-green': record.proceduresStatus === 2
            }"
          >
            {{
              record.proceduresStatus === 0
                ? '待办理'
                : record.proceduresStatus === 1
                ? '办理中'
                : '已办理'
            }}
          </span>
        </template>
      </a-table-column>
      <a-table-column
        :width="100"
        fixed="right"
        :cell-style="{
          textAlign: 'left'
        }"
      >
        <template #title>
          <a-tooltip content="是否显示排序">
            <icon-font
              type="icon-filter-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer'
              }"
              @click="isFilter"
            />
          </a-tooltip>
          <a-tooltip content="表头设置">
            <icon-font
              type="icon-setting-def"
              :size="26"
              :style="{
                cursor: 'pointer'
              }"
              @click="isHeaderSetting"
            />
          </a-tooltip>
        </template>
        <template #cell="{ record }">
          <div style="float: left; display: flex">
            <a-tooltip content="员工档案">
              <icon-font
                type="icon-details-def"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goDetail(record.id, record.useTemplate.ownerType)"
              />
            </a-tooltip>

            <a-tooltip content="删除" position="left">
              <a-popconfirm
                content="是否确认删除该条数据?"
                position="left"
                @ok="del(record.id)"
              >
                <IconFont
                  type="icon-delete"
                  :size="26"
                  :style="{
                    cursor: 'pointer'
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
            <a-tooltip content="办理入职" v-if="record.proceduresStatus !== 2">
              <a-dropdown
                @select="(value: number, e: Event, id: number) => handleEntryDropdown(value, e, record)"
              >
                <icon-font
                  type="icon-ruzhibanli"
                  :size="26"
                  :style="{
                    cursor: 'pointer'
                  }"
                />
                <template #content>
                  <a-doption :value="1" v-if="record.epStatus !== 2"
                    >{{
                      record.epStatus == 0
                        ? '创建入职手续'
                        : record.epStatus === 1
                        ? '配置入职手续'
                        : ''
                    }}
                  </a-doption>
                  <a-doption :value="2" v-if="record.onboardingStatus <= 1"
                    >入职方案审批</a-doption
                  >
                  <a-doption :value="2" v-else>查看审批详情</a-doption>
                  <a-doption
                    :value="3"
                    v-if="
                      record.onboardingStatus === 4 &&
                      record.contractStatus < 10
                    "
                    >发起合同签署</a-doption
                  >
                  <!-- v-role="{ role: 'contract-signing' }" -->

                  <a-doption :value="4">放弃入职</a-doption>
                </template>
              </a-dropdown>
            </a-tooltip>
          </div>
        </template>
      </a-table-column>
    </TableTurn>
  </ContentCard>
  <FormHeaderControlSetting
    title="员工花名册表头设置"
    v-model:visible="modalVisiable"
    :result-list="headerSetting"
    @headerSave="headerSave"
    :orginHeaderList="orginHeaderList.headerListCode"
    :forbidList="forbidList"
  >
  </FormHeaderControlSetting>
  <ExportControlSetting
    v-model:visible="exportSettingVisible"
    title="员工花名册导出设置"
    :result-list="exportHeaderList"
    @headerSave="exportSave"
    :forbidList="exportyForbidList"
  >
  </ExportControlSetting>
  <ImportModal
    v-model:visible="importVisible"
    :func="getHeaderData"
    :headerList="headerSetting"
    :forbidList="forbidList"
    @importSave="importSave"
    @importHeaderSave="importHeaderSave"
    title="员工花名册导入"
  >
  </ImportModal>
</template>

<script lang="tsx" setup>
import {
  placeSplice,
  downloadExcelFile,
  dataTreeFilter,
  flatTree
} from '@/utils/utils';
import {
  GetHumanRosterList,
  DelHumanRosterList,
  ExportHumanRosterList
} from '@/apis/management/human/humanRoster';
import { Message } from '@arco-design/web-vue';
import { GetBusinessModalData } from '@/apis/controltotal';
import { GetUserDetail } from '@/apis/management/user';
import {
  PostImportTemplate,
  GetHeaderSetting,
  PostHeaderSetting,
  PutHeaderSetting
} from '@/apis/management/base';
import { getPositionHierarchyList } from '@/apis/management/organization/baseSetting/PositionSystem/index';
import { GetOrganizationListDetail } from '@/apis/management/organization/organizationManagement';
import { getPositionList, getFlatDept } from '@/utils/common';
import TableControlShow from '@/components/TableControlShow/index.vue';
import IssuingCertificateModal from './IssuingCertificate/IssuingCertificateModal.vue';
import { getProcessByAcronym } from '@/apis/approve/index';
import { useMenusStore } from '@/store';
import { ChangeHumanInductionState } from '@/apis/management/personnel/changeManagement/inductionManagement';
import { Modal } from '@arco-design/web-vue';
// import HumenNumberCard from './Components/HumenNumberCard.vue';

const router = useRouter();
const menusStore = useMenusStore();
const title = '员工花名册';

const breadCrumb: string[] = ['人事', '人员管理', '员工花名册'];

let singleSelectId = 0; // 储存单个id
/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);
const selectedListData = computed(() => tableRef.value.selectedListData);

let tableRef = ref(); // 储存table的ref
let forbidList: string[] = [
  'C62B8DC31189847E0972B5D8F721404B1', // 姓名
  'CDC80FC12D1DE43018D098E8322D0F966', // 工号
  'C3384BE6E60C341D68B8180DA04A1C4E1', // 手机号码
  'C7341027925C943708F3AEF98703ECC47', // 职位
  'CA8ABCC1480744557B3014C3454465A7E', // 公司
  'CED44AC9966904CD1AB546D309903727C' // 部门
]; // 必选的表头

let refIssuingCertificateModal = ref();
let batchSelect = (val: any) => {
  if (val === 7) {
    refIssuingCertificateModal.value.openModal(tableRef.value.selectedList);
  }
};
const addHeader = async () => {
  try {
    const {
      funcCtlInfos: { children }
    } = (await GetBusinessModalData({
      funcCode: 'SER_FUNCA0132DDBB9F14638815C4F0C7C476435'
    })) as any;

    let headerListCode: any = [];
    children.forEach((item1: any) => {
      const { subRelDetail, cnName, subCode } = item1.subDetail;
      subRelDetail?.forEach((item2: any, index2: number) => {
        headerListCode.push(item2.ctlCode);
      });
    });
    await PostHeaderSetting({
      userId: +(localStorage.getItem('userId') as string),
      ownerFuncType: 3,
      headerListCode: headerListCode.join(',')
    });
    getData();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 批量人事操作数据
const batchOperation = [
  {
    label: '新增员工标签',
    value: 1,
    icon: 'icon-a-Tag-onebiaoqian'
  },
  {
    label: '邀请员工完善档案',
    value: 2,
    icon: 'icon-a-Tag-onebiaoqian'
  },
  // {
  //   label: '工卡制作',
  //   value: 3,
  //   icon: 'icon-a-Tag-onebiaoqian'
  // },
  {
    label: '发送短信通知',
    value: 4,
    icon: 'icon-a-Tag-onebiaoqian'
  },
  // {
  //   label: '发送人才测评',
  //   value: 5,
  //   icon: 'icon-a-Tag-onebiaoqian'
  // },
  // {
  //   label: '发起背景调查',
  //   value: 6,
  //   icon: 'icon-a-Tag-onebiaoqian'
  // },
  {
    label: '开具证明',
    value: 7,
    icon: 'icon-a-Tag-onebiaoqian'
  }
];

// 更多功能按钮
const moreControl = [
  {
    label: '员工成长对比',
    value: 1
  },
  {
    label: '批量删除员工',
    value: 2
  },
  {
    label: '花名册备份',
    value: 3
  }
];

const add = () => {
  router.push({
    name: 'AddNewemployee',
    query: {
      progress: 4
    }
  });
};

// 修改折叠面板状态
const changeCollapse = () => {
  if (isCollapse.value === '1') {
    isCollapse.value = '2';
  } else {
    isCollapse.value = '1';
  }
};

// 表格属性
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
});

const placeCtlCode = [
  'C02BE308AEE674E3F95335AED60682954',
  'CF058C6BF648940BA96B49495CC768E20'
]; //户籍所在地、籍贯相关code
// 重组树形数据所需子方法
let nameSearch = ref(''), // 姓名搜索框
  phoneSearch = ref(''); // 手机搜索框

// 获取表格数据
const getTableData = async (pageData?: any) => {
  try {
    // let search = 0;
    // if (nameSearch.value !== '') search++;
    // if (phoneSearch.value !== '') search++;
    const res: any = await GetHumanRosterList({
      ...pageData,
      typeName: '4,5,6,9,10,11,12,13,14,15',
      name: nameSearch.value,
      // ctlCode: 'C62B8DC31189847E0972B5D8F721404B1',
      // search: search !== 0 ? search + '' : '',
      mobile: phoneSearch.value
    });
    res?.content?.forEach((item: any) => {
      item.ctlValue?.forEach((element: any) => {
        item[element.ctlCode] = element.ctlValue;
      });
      item.status = handleStatus(item);
    });
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

// 处理办理状态
const handleStatus = (data: any) => {
  if (data.onboardingStatus <= 1 && data.proceduresStatus === 0) {
    return '待办理';
  } else if (data.onboardingStatus === 4 && data.proceduresStatus === 2) {
    return '已办理';
  } else return '办理中';
};

const onSearch = () => {
  refresh();
};

let isCollapse = ref('1'); // 是否展开员工统计数据
let numberList = reactive({
  list1: [
    {
      name: '在职',
      value: 0
    },
    {
      name: '全职',
      value: 0
    },
    {
      name: '实习生',
      value: 0
    },
    {
      name: '兼职',
      value: 0
    }
  ], // 全职、实习生、兼职
  list2: [
    {
      name: '正式',
      value: 0
    },
    {
      name: '试用期',
      value: 0
    },
    {
      name: '待离职',
      value: 0
    }
  ], // 正式、试用期、预离职
  list3: [
    {
      name: '历史总人数',
      value: 0
    },
    {
      name: '历史已离职',
      value: 0
    }
  ] // 历史总人数、历史已离职
});

let headerSetting = ref<any>([]), // 当前的表头数据
  orginHeaderList = ref([]), // 原始的表头数据
  deptList = ref([]), // 平级部门数据
  positionList = ref([]), // 职位数据
  positionHierarchyList = ref([]); // 职位层级数据
// 获取其他数据
const getData = async () => {
  try {
    // 这里要先获取表头的数据，不然数据量太大会使表格横向滚动条失效
    const userId = +(localStorage.getItem('userId') as string);
    const headerSettingRes = // 获取人员表头
      await GetHeaderSetting({
        ownerFuncType: 3,
        userId
      });
    const businessModalDataRes = await GetBusinessModalData({
      funcCode: 'SER_FUNCA0132DDBB9F14638815C4F0C7C476435'
    });
    orginHeaderList.value = headerSettingRes;
    headerSetting.value = [];
    const headerChildren = businessModalDataRes.funcCtlInfos.children;
    headerChildren.forEach((child: any, index: number) => {
      headerSetting.value.push({
        collectionName: child.subDetail.cnName,
        collectionCode: child.subDetail.subCode,
        heads: child.subDetail.subRelDetail.map((subDetail: any) => {
          const isDefault = headerSettingRes.headerListCode.includes(
            subDetail.ctlCode
          );
          return {
            ...subDetail,
            isDefault
          };
        })
      });
    });
    exportHeaderList.value = headerSetting.value;
    if (headerSettingRes.headerListCode.length < 1) {
      addHeader();
    }
    const [deptRes, positionListRes, userDetailRes, positionHierarchyListRes] =
      await Promise.all([
        // 获取平级的组织数据
        getFlatDept(),
        // 获取所有职位数据
        getPositionList(),
        // 获取控件人员数据
        // 人员详情
        GetUserDetail({
          id: 113
        }),
        // 获取职位层级数据
        getPositionHierarchyList({
          pageNumber: 0,
          pageSize: -1
        })
      ]);
    deptList.value = deptRes;
    positionList.value = flatTree(dataTreeFilter(positionListRes.content));
    positionHierarchyList.value = positionHierarchyListRes.content;
    // 获取组织详情数据
    const orgDetailRes = await GetOrganizationListDetail({
      id: +userDetailRes.date.organizationId
    });

    console.log('========= positionList.value===========================');
    console.log(orgDetailRes);
    console.log('====================================');

    const {
      onJob,
      fullTime,
      practice,
      partTime,
      formal,
      probation,
      waitDepart,
      historyNum,
      historyDepart
    } = orgDetailRes;
    numberList.list1[0].value = onJob;
    numberList.list1[0].value = fullTime;
    numberList.list1[1].value = practice;
    numberList.list1[2].value = partTime;
    numberList.list2[0].value = formal;
    numberList.list2[1].value = probation;
    numberList.list2[2].value = waitDepart;
    numberList.list3[0].value = historyNum;
    numberList.list3[1].value = historyDepart;
  } catch (error: unknown) {
    console.log(error);
  }
};
getData();

let modalVisiable = ref(false); // 判断是否显示表头

// 是否显示表头
const isHeaderSetting = async () => {
  try {
    modalVisiable.value = !modalVisiable.value;
  } catch (error: unknown) {
    console.log(error);
  }
};

// 在表格上显示的表头
const selectedHeader = computed(() => {
  const selectedHeaders: any[] = [];
  headerSetting.value.forEach((headerGroup: any, index: number) => {
    let defaultHeaders = headerGroup.heads.filter(
      (header: any) => header.isDefault === true
    );
    defaultHeaders = defaultHeaders.map((el: any) => {
      const sort = orginHeaderList.value.headerListCode
        .split(',')
        .findIndex((el2: any) => el2 === el.ctlCode);
      return {
        ...el,
        sort
      };
    });
    selectedHeaders.push(...defaultHeaders);
  });

  selectedHeaders.sort((a, b) => a.sort - b.sort);
  // 将姓名移到最前面
  const nameHeaderIndex = selectedHeaders.findIndex(
    (header) => header.ctlCode === 'C62B8DC31189847E0972B5D8F721404B1'
  );
  if (nameHeaderIndex !== -1) {
    selectedHeaders.unshift(...selectedHeaders.splice(nameHeaderIndex, 1));
  }
  return selectedHeaders;
});

// 表头设置返回的自定义事件
const headerSave = async (totalList: any, used: any, unused: any) => {
  try {
    const id = orginHeaderList.value.id;
    const headerListCode = used.map((item: any) => item.ctlCode).join(',');
    await PutHeaderSetting({
      id,
      userId: +localStorage.getItem('userId')!,
      ownerFuncType: 3,
      headerListCode
    });
    headerSetting.value = totalList;
    orginHeaderList.value.headerListCode = headerListCode;
  } catch (error) {
    console.log(error);
  }
};

// 表格中需要特殊渲染的template
const showCtlCodeArr = [
  'C63EC32DCE9CC4BE6AC7649E23234A542',
  'C9A9EF3DFFFC84AAFB97443DEE8E5B8CC',
  'CB4163C72FA5E45D38302983E8A66801E',
  'CE183DF5A547A4728A60F9AFDF3C53194',
  'CA8ABCC1480744557B3014C3454465A7E',
  'CED44AC9966904CD1AB546D309903727C',
  'C7341027925C943708F3AEF98703ECC47',
  'C1F5AA49A78EC4B4FBD487F4D5887E576',
  'C50267C6B8E104B0C91EDD25BCAE35609',
  'CECEBAA743F9B4160B40A5A3E78588712'
  // 'C62B8DC31189847E0972B5D8F721404B1'
];

// 前往入职办理列表
const goHandleEntry = (record: any) => {
  router.push({
    name: 'EntryManagement',
    query: {
      name: record.name
    }
  });
};

const approveVisible = ref(false);
const approveList = ref([]); //流程列表
/**
 * 获取流程列表
 */
const getApproveList = async () => {
  if (approveList.value.length) return;
  const res = await getProcessByAcronym('onboarding_plan');
  approveList.value = res?.list || [];
};
const selectedUserId = ref(0); //选中的用户
/**
 * 发起入职审批
 */
const selectProcess = (processId: number) => {
  if (!processId) return;
  router.push({
    name: 'InitiateApproval',
    query: { processId, userId: selectedUserId.value }
  });
};

// 表格中的三个小点按钮的下拉菜单
const handleEntryDropdown = async (
  key: number,
  e: Event | string,
  record: any
) => {
  try {
    let title = e?.target?.innerText;
    let content: any;
    let onOk: (() => void) | undefined;
    // let title;
    switch (key) {
      case 1:
        router.push({
          name: 'Formalities',
          query: { id: record.id }
        });
        break;
      case 2:
        getApproveList();
        approveVisible.value = true;
        selectedUserId.value = record.id;
        break;
      // 审批
      case 3:
        {
          router.push({
            name: 'ContractWaitSigned',
            query: {
              name: record.name
            }
          });
        }
        menusStore.setMenuKey('7');
        menusStore.setCurrMenus('contract');
        break;
      // 放弃入职
      case 4:
        content = (
          <>
            <h3>是否确认放弃入职？</h3>
          </>
        );
        onOk = async () => {
          await ChangeHumanInductionState({
            ids: [record.id],
            type: 8
          });
          refresh();
        };
        break;
      // 确认入职
      case 5:
        content = (
          <>
            <h3>是否确认入职？</h3>
          </>
        );
        onOk = async () => {
          await ChangeHumanInductionState({
            ids: [record.id],
            type: 5
          });
          refresh();
        };
        break;
      default:
        break;
    }
    if (key !== 1 && key !== 2 && key !== 3)
      Modal.open({
        title,
        content,
        onOk
      });
  } catch (error: unknown) {
    console.log(error);
  }
};

// 前往详情
const goDetail = (id: number, ownerType: number) => {
  router.push({
    name: 'HumanRosterDetail',
    query: {
      id,
      ownerType
    }
  });
};

//删除
const del = async (id: number) => {
  if (selectedList.value.length > 0) {
    await DelHumanRosterList({
      ids: selectedList.value
    });
    tableRef.value.selectedList = [];
  } else
    await DelHumanRosterList({
      ids: [id]
    });
  refresh();
};

const getHeaderData = () => {
  try {
    return GetHeaderSetting({
      type: 3, // 人员花名册表头默认传3,
      userId: +(localStorage.getItem('userId') as string)
    });
  } catch (error: unknown) {
    console.log(error);
  }
};

let importVisible = ref(false); // 导入弹出框
// 下载导入模板
const importHeaderSave = async (used: any, userId: number) => {
  try {
    // let excels: any = [];
    let code: any = [],
      name: any = [],
      necessary: any = [];
    used.forEach((item: any) => {
      code.push(item.code);
      name.push(item.name);
      if (forbidList.includes(item.code)) necessary.push('true');
      else necessary.push('false');
    });
    const formData = new FormData();
    formData.append('code', code + '');
    formData.append('name', name + '');
    formData.append('necessary', necessary + '');
    const res = await PostImportTemplate(formData);
    downloadExcelFile(res, '员工花名册导入模板');
  } catch (error: unknown) {
    console.log(error);
  }
};

const importSave = async (file: any) => {
  try {
    let formData = new FormData();
    formData.append('data', file.file);
    // await ImportOrganizationList(formData);
  } catch (error: unknown) {
    console.log(error);
  }
};

let exportSettingVisible = ref(false);
let exportHeaderList = ref(); // 接口获取过来的原始表头数据
let exportyForbidList = [
  'C30BBF36A5AF541F7A2657671DEE2EDD6', // 组织名称
  'CB1AAC9E508714223BA4D1596FE690877', // 组织编码
  'C3D33FA57216F4968BDE51C31D623FC09', // 组织类型
  'CD25749DBA68E4BF3BCA616DD63751CB7', // 编制人数
  'CB0C63F38283045F58FFF1B1EABE5D151', // 组织负责人
  'CE009C2E2B542409D815F0D3D54FE0E2B' // 工作地点
]; // 必选的表头

const exportSave = async (used: any) => {
  try {
    let models = [];
    models = used.map((el: any) => {
      return {
        name: el.ctlCnName,
        code: el.ctlCode,
        state: 1
      };
    });
    const res = await ExportHumanRosterList({
      models
    });
    const file = new Blob([res.data], { type: 'application/xlsx' });
    const changeUrl = window.webkitURL.createObjectURL(file);
    let downloadElement: any = document.createElement('a');
    downloadElement.download = '员工花名册' + '.xlsx';
    downloadElement.href = changeUrl;
    downloadElement.click();
    downloadElement = undefined;
    window.URL.revokeObjectURL(changeUrl);
  } catch (error: unknown) {
    console.log(error);
  }
};

const refresh = () => {
  tableRef.value.loadData();
};
</script>

<style lang="less" scoped>
.collapseBtn {
  position: absolute;
  right: 0;
  top: 60px;
  cursor: pointer;
}
// .container {
//   padding: 10px 20px;
//   .box {
//     margin-bottom: 16px;
//     display: flex;
//     &-item {
//       flex: 1;
//     }
//     &-item:not(:last-child) {
//       margin-right: 16px;
//     }
//   }
//   .header {
//     display: flex;
//     justify-content: space-between;
//     &-front {
//       position: relative;
//       line-height: 30px;
//     }
//     // .commonBtns {
//     //   background-color: rgb(var(--primary-1));
//     // }
//   }
//   .main {
//     margin-top: 20px;
//   }
// }
:deep(.arco-collapse-item-content) {
  background-color: #fff;
  padding: 0;
}

:deep(.arco-collapse-item-active > .arco-collapse-item-header) {
  display: none;
  border: none;
}
</style>
